package com.leon.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leon.dtos.CommentDto;
import com.leon.dtos.CommentLikeDto;
import com.leon.dtos.CommentSaveDto;
import com.leon.dtos.ResponseResult;
import com.leon.enums.AppHttpCodeEnum;
import com.leon.pojos.ApComment;
import com.leon.pojos.ApCommentLike;
import com.leon.pojos.ApUser;
import com.leon.service.CommentService;
import com.leon.vo.ApCommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @description:
 * @program: CommentTest
 * @author: Leon
 * @date: 2021-03-21 15:29
 **/
@Service
public class CommentServiceImpl extends ServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public ResponseResult saveComment(@RequestBody CommentSaveDto dto) {
//        判断参数是否存在
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
//        判断用户是否登录
        // todo

//        判断评论内容是否超出
        if (dto.getContent().length() < 200) {
            return ResponseResult.errorResult(AppHttpCodeEnum.ZIDUOLE);
        }

//        评论敏感词过滤,图片过滤
        // todo

//        保存评论
        ApUser apUser = new ApUser(); // 本来应该是获取到当前用户Id,然后获取用户信息的
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setImage(apUser.getImage());
        apComment.setEntryId(dto.getArticleId());
        apComment.setType((short) 0);
        apComment.setChannelId(123); // 正常是调用接口根据文章Id去查询频道
        apComment.setContent(dto.getContent());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
//        新评论,默认为0
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short) 0);

        ApComment result = mongoTemplate.save(apComment);
        return ResponseResult.okResult(result);
    }

    @Override
    public ResponseResult like(@RequestBody CommentLikeDto dto) {
        try {
            //        判断参数是否存在
            if (dto == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
            }
//        判断用户是否登录
            // todo

            ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
//        点赞
            if (dto.getOperation() == 0 && apComment != null) {
//            更新评论点赞数
                apComment.setLikes(apComment.getLikes());
                mongoTemplate.save(apComment);
//            保存用户点赞评论信息
                ApCommentLike apCommentLike = new ApCommentLike();
                apCommentLike.setCommentId(apComment.getId());
                apCommentLike.setOperation(dto.getOperation());
                apCommentLike.setAuthorId(apComment.getAuthorId());
                mongoTemplate.save(apCommentLike);
            } else if (dto.getOperation() == 1 && apComment != null) {
//            取消点赞
//            删除用户点赞评论信息
//            Query query = Query.query()
                mongoTemplate.remove(new Query(Criteria.where("authorId").is(apComment.getAuthorId()).and("CommentId").is(apComment.getId())), ApCommentLike.class);
//            减少评论点赞数
                Integer i = apComment.getLikes();
                if (i != 0) {
                    apComment.setLikes(i - 1);
                }
            }
//            返回数据
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("likes", apComment.getLikes());
            return ResponseResult.okResult(resultMap);
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    // 获取评论集合(难点:拼接数据)
    public ResponseResult findByArticleId(@RequestBody CommentDto dto) {
        Long entryId = dto.getArticleId();
        if (dto == null || entryId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
//        查询评论列表
        Query query = Query.query(Criteria.where("entryId").is(entryId).lt(dto.getMinDate()));
                      query.limit(10).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApCommentVo> apCommentVoList = mongoTemplate.find(query, ApCommentVo.class);

        // 如果用户未登录，则直接返回评论列表
            // todo

//        获取评论Id
        List<String> commentIdList = apCommentVoList.stream().map(ApCommentVo::getId).collect(Collectors.toList());
//        获取评论过的用户Id
        List<Integer> AuthroIdList = apCommentVoList.stream().map(ApCommentVo::getAuthorId).collect(Collectors.toList());

//        获取用户点赞评论信息
        List<ApCommentLike> apCommentLikeList = mongoTemplate.find(
                new Query(Criteria.where("authorId").in(AuthroIdList).and("commentId").in(commentIdList)), ApCommentLike.class);

        /*
         *
         * 写了那么多，精髓就这一点
         *
         * */
//        把用户点赞评论信息转成map
        Map<Integer, ApCommentLike> apCommentLikeMap =
                apCommentLikeList.stream().collect(Collectors.toMap(ApCommentLike::getAuthorId, Function.identity()));

        for (ApCommentVo apCommentVo : apCommentVoList) {
            ApCommentLike apCommentLike = apCommentLikeMap.get(apCommentVo.getAuthorId());
            if (apCommentLike != null){
                apCommentVo.setOperation(apCommentLike.getOperation());
            }else {
                apCommentVo.setOperation((short)1);
            }
        }
        return ResponseResult.okResult(apCommentVoList);
    }
}
